package com.itheima.controller;

import com.itheima.domain.Message;
import com.itheima.domain.User;
import com.itheima.service.MessageService;
import com.itheima.until.Code;
import com.itheima.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/message")
public class MessageController {

    private final MessageService messageService;

    @Autowired
    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @ResponseBody
    @RequestMapping("/conversationList")
    public List<Message> conversationList(HttpSession session) {
        User user = (User) session.getAttribute("user");
        String userId = String.valueOf(user.getUid());

        return messageService.conversationList(userId);
    }

    @ResponseBody
    @RequestMapping("conversation")
    public List<Message> conversation(HttpSession session, String partnerId) {
        User user = (User) session.getAttribute("user");
        String userId = String.valueOf(user.getUid());

        List<Message> conversation = messageService.conversation(userId, partnerId);
        if(conversation.size() == 0){
            Message message = new Message();
            message.setSendId(userId);
            message.setReceiveId(partnerId);
            message.setContent("你好我是"+user.getNickname());
            messageService.sendMessage(message);
        }

        return messageService.conversation(userId, partnerId);
    }

    @ResponseBody
    @RequestMapping("/sendMessage")
    public Result sendMessage(@RequestBody Message message) {

        messageService.sendMessage(message);

        return new Result(Code.SAVE_OK, message);
    }
}

